package com.bzchao.ds.demo.tenant.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bzchao.ds.core.config.DynamicDataSource;
import com.bzchao.ds.core.dao.DataSourceDao;
import com.bzchao.ds.demo.tenant.entity.TenantInfo;
import com.bzchao.ds.demo.tenant.mapper.TenantInfoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "租户")
@RestController
@RequestMapping("/tenant")
public class TenantController {
    @Resource
    private TenantInfoMapper tenantInfoMapper;
    @Resource
    private DataSourceDao dataSourceDao;
    @Autowired
    private DynamicDataSource dynamicDataSource;

    @ApiOperation(value = "查询所有")
    @GetMapping("all")
    public List<TenantInfo> findAll() {
        return tenantInfoMapper.selectList(new LambdaQueryWrapper<>());
    }

    @ApiOperation(value = "新增")
    @PostMapping("add")
    public TenantInfo add(@RequestBody TenantInfo tenant) {
        log.info("tenantId:{}", DynamicDataSource.getConnectionId());
        tenantInfoMapper.insert(tenant);
        log.info("{}", tenant);

        //重新加载数据库连接
        List<Map<String, String>> mapList = dataSourceDao.listEnableDataSource();
        dynamicDataSource.setDataSources(mapList);

        return tenant;
    }

    @ApiOperation(value = "更新")
    @PostMapping("update")
    public TenantInfo update(@RequestBody TenantInfo tenant) {
        log.info("tenantId:{}", DynamicDataSource.getConnectionId());
        tenantInfoMapper.updateById(tenant);
        log.info("{}", tenant);

        //重新加载数据库连接
        List<Map<String, String>> mapList = dataSourceDao.listEnableDataSource();
        dynamicDataSource.setDataSources(mapList);

        return tenant;
    }
}
